package utils

import (
	"errors"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

type Claims struct {
	Id       uint
	Username string
	LoginId  string
	jwt.RegisteredClaims
}

var JwtSecret = []byte("luo-xiao-hao-123")

// 生成 JWT Token
func GenerateToken(id uint, username string, loginId string, expireTime time.Time) (string, time.Time, error) {

	// 创建 Claims
	claims := &Claims{
		Id:       id,
		Username: username,
		LoginId:  loginId,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expireTime),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
			Subject:   username,
		},
	}

	// 生成 Token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	// 对 token进行签名 ，JwtSecret 是秘钥
	tokenString, err := token.SignedString(JwtSecret)

	return tokenString, expireTime, err
}

// 解析和验证 JWT Token
func ParseToken(tokenString string) (*Claims, error) {
	// 解析 Token
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return JwtSecret, nil
	})

	if err != nil {
		return nil, err
	}

	// 验证 Token
	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
		return claims, nil
	}

	return nil, errors.New("invalid token")
}

// 从请求头中提取 Token
func ExtractTokenFromHeader(authHeader string) (string, error) {
	if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
		return authHeader[7:], nil
	}
	return "", errors.New("invalid authorization header format")
}
